import { defineComponent, onMounted, shallowRef, watch, type PropType, onUnmounted } from 'vue'
import { init, type EChartsOption, type EChartsType } from 'echarts'

const props = {
  options: Object as PropType<EChartsOption | undefined | null>,
  loading: Boolean as PropType<Boolean | undefined>
}

export default defineComponent({
  name: 'BaseChart',
  props,
  setup(props) {
    const self = shallowRef<HTMLElement | null>(null)
    const chart = shallowRef<EChartsType | null>(null)

    const handleResize = () => {
      chart.value?.resize()
    }
    const handleOptions = () => {
      if (!chart.value) return
      chart.value.setOption(props.options || {}, true)
    }
    const handleLoading = () => {
      if (!chart.value) return
      if (!props.loading) return chart.value.hideLoading()
      chart.value.showLoading({
        text: '加载中...',
        color: '#1BD1FF',
        textColor: '#1BD1FF',
        maskColor: 'rgba(52, 152, 219, 0.15)'
      })
    }

    watch(() => props.options, handleOptions, { flush: 'post' })
    watch(() => props.loading, handleLoading, { flush: 'post' })
    onMounted(() => {
      chart.value = init(self.value, 'base')
      handleOptions()
      handleResize()
      window.addEventListener('resize', handleResize)
    })
    onUnmounted(() => window.removeEventListener('resize', handleResize))

    return {
      self
    }
  },
  render() {
    return <div ref="self"></div>
  }
})
